import tkinter as tk
from tkinter import ttk, messagebox
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import threading
import time

from modules.orbit_calculator import OrbitCalculator
from modules.link_budget import LinkBudgetCalculator
from modules.visualization import SatelliteVisualizer

class MainApplication:
    """主应用程序类"""
    
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("卫星通信仿真软件 v1.0")
        self.root.geometry("1200x800")
        
        # 初始化模块
        self.orbit_calc = OrbitCalculator()
        self.link_calc = LinkBudgetCalculator()
        self.visualizer = SatelliteVisualizer()
        
        # 创建GUI组件
        self._create_menu()
        self._create_main_frame()
        self._create_control_panel()
        self._create_visualization_panel()
        
        # 仿真状态
        self.is_running = False
        self.simulation_thread = None
        
    def _create_menu(self):
        """创建菜单栏"""
        menubar = tk.Menu(self.root)
        
        # 文件菜单
        file_menu = tk.Menu(menubar, tearoff=0)
        file_menu.add_command(label="新建仿真", command=self._new_simulation)
        file_menu.add_command(label="保存配置", command=self._save_config)
        file_menu.add_command(label="加载配置", command=self._load_config)
        file_menu.add_separator()
        file_menu.add_command(label="退出", command=self.root.quit)
        menubar.add_cascade(label="文件", menu=file_menu)
        
        # 帮助菜单
        help_menu = tk.Menu(menubar, tearoff=0)
        help_menu.add_command(label="使用说明", command=self._show_help)
        help_menu.add_command(label="关于", command=self._show_about)
        menubar.add_cascade(label="帮助", menu=help_menu)
        
        self.root.config(menu=menubar)
    
    def _create_main_frame(self):
        """创建主框架"""
        self.main_frame = ttk.Frame(self.root)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
    def _create_control_panel(self):
        """创建控制面板"""
        control_frame = ttk.LabelFrame(self.main_frame, text="控制面板", padding=10)
        control_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10))
        
        # 轨道参数
        orbit_frame = ttk.LabelFrame(control_frame, text="轨道参数", padding=5)
        orbit_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(orbit_frame, text="轨道高度 (km):").grid(row=0, column=0, sticky=tk.W)
        self.altitude_var = tk.DoubleVar(value=550)
        ttk.Entry(orbit_frame, textvariable=self.altitude_var, width=10).grid(row=0, column=1)
        
        ttk.Label(orbit_frame, text="轨道倾角 (°):").grid(row=1, column=0, sticky=tk.W)
        self.inclination_var = tk.DoubleVar(value=53)
        ttk.Entry(orbit_frame, textvariable=self.inclination_var, width=10).grid(row=1, column=1)
        
        # 通信参数
        comm_frame = ttk.LabelFrame(control_frame, text="通信参数", padding=5)
        comm_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(comm_frame, text="发射功率 (dBm):").grid(row=0, column=0, sticky=tk.W)
        self.tx_power_var = tk.DoubleVar(value=30)
        ttk.Entry(comm_frame, textvariable=self.tx_power_var, width=10).grid(row=0, column=1)
        
        ttk.Label(comm_frame, text="频率 (GHz):").grid(row=1, column=0, sticky=tk.W)
        self.frequency_var = tk.DoubleVar(value=2.4)
        ttk.Entry(comm_frame, textvariable=self.frequency_var, width=10).grid(row=1, column=1)
        
        # 控制按钮
        button_frame = ttk.Frame(control_frame)
        button_frame.pack(fill=tk.X, pady=10)
        
        self.start_button = ttk.Button(button_frame, text="开始仿真", command=self._start_simulation)
        self.start_button.pack(fill=tk.X, pady=2)
        
        self.stop_button = ttk.Button(button_frame, text="停止仿真", command=self._stop_simulation, state=tk.DISABLED)
        self.stop_button.pack(fill=tk.X, pady=2)
        
        self.reset_button = ttk.Button(button_frame, text="重置", command=self._reset_simulation)
        self.reset_button.pack(fill=tk.X, pady=2)
    
    def _create_visualization_panel(self):
        """创建可视化面板"""
        viz_frame = ttk.LabelFrame(self.main_frame, text="可视化面板", padding=10)
        viz_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 创建matplotlib图形
        self.fig = Figure(figsize=(10, 8), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.fig, viz_frame)
        self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        
        # 初始化可视化
        self.visualizer.setup_plot(self.fig)
    
    def _start_simulation(self):
        """开始仿真"""
        if not self.is_running:
            self.is_running = True
            self.start_button.config(state=tk.DISABLED)
            self.stop_button.config(state=tk.NORMAL)
            
            # 获取参数
            altitude = self.altitude_var.get()
            inclination = self.inclination_var.get()
            tx_power = self.tx_power_var.get()
            frequency = self.frequency_var.get()
            
            # 配置模块
            self.orbit_calc.set_parameters(altitude, inclination)
            self.link_calc.set_parameters(tx_power, frequency)
            
            # 启动仿真线程
            self.simulation_thread = threading.Thread(target=self._run_simulation)
            self.simulation_thread.daemon = True
            self.simulation_thread.start()
    
    def _stop_simulation(self):
        """停止仿真"""
        self.is_running = False
        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)
    
    def _reset_simulation(self):
        """重置仿真"""
        self._stop_simulation()
        self.visualizer.reset()
        self.canvas.draw()
    
    def _run_simulation(self):
        """运行仿真循环"""
        while self.is_running:
            # 计算轨道位置
            position = self.orbit_calc.get_current_position()
            
            # 计算链路预算
            link_params = self.link_calc.calculate_link_budget(position)
            
            # 更新可视化
            self.root.after(0, self._update_visualization, position, link_params)
            
            time.sleep(0.1)
    
    def _update_visualization(self, position, link_params):
        """更新可视化"""
        self.visualizer.update_plot(position, link_params)
        self.canvas.draw()
    
    def _new_simulation(self):
        """新建仿真"""
        self._reset_simulation()
        messagebox.showinfo("提示", "已创建新的仿真项目")
    
    def _save_config(self):
        """保存配置"""
        messagebox.showinfo("提示", "配置已保存")
    
    def _load_config(self):
        """加载配置"""
        messagebox.showinfo("提示", "配置已加载")
    
    def _show_help(self):
        """显示帮助"""
        help_text = """
卫星通信仿真软件使用说明：

1. 在控制面板设置轨道参数和通信参数
2. 点击"开始仿真"按钮启动仿真
3. 可视化面板将显示卫星轨道和信号覆盖范围
4. 可以随时调整参数并观察变化

技术支持：如有问题请联系开发团队
        """
        messagebox.showinfo("使用说明", help_text)
    
    def _show_about(self):
        """显示关于信息"""
        about_text = """
卫星通信仿真软件 v1.0

基于Python tkinter和matplotlib开发
用于模拟和可视化卫星通信过程

开发团队：卫星通信仿真项目组
版本：1.0.0
        """
        messagebox.showinfo("关于", about_text)
    
    def run(self):
        """运行应用程序"""
        self.root.mainloop()